<template>
  <view class="container">

    <!-- 头像设置区域 -->
    <view class="avatar-section">
      <view class="avatar-container" @click="handleAvatarChange">
        <image class="avatar" :src="userProfile.avatarUrl" mode="aspectFill"></image>
        <view class="camera-icon">
          <image src="/static/icons/wechat-icon.svg" mode="aspectFit" style="width: 14px; height: 14px;"></image>
        </view>
      </view>
      <text class="avatar-hint">点击更换头像 本月剩余修改5/5次</text>
    </view>

    <!-- 表单区域 -->
    <view class="form-section">
      <!-- 昵称 -->
      <view class="form-item">
        <text class="form-label">昵称</text>
        <input class="form-input" v-model="userProfile.userName" type="text" placeholder="请输入昵称" placeholder-style="color: #cccccc;"></input>
      </view>

      <!-- 性别 -->
      <view class="form-item">
        <text class="form-label">性别</text>
        <view class="gender-selector">
          <view :class="['gender-btn', userProfile.gender === 'male' ? 'gender-btn-active' : 'gender-btn-inactive']" @click="handleGenderSelect('male')">男</view>
          <view :class="['gender-btn', userProfile.gender === 'female' ? 'gender-btn-active' : 'gender-btn-inactive']" @click="handleGenderSelect('female')">女</view>
        </view>
      </view>

      <!-- 简介 -->
      <view class="form-item" @click="handleBioEdit">
        <text class="form-label">简介</text>
        <text class="form-value">{{ userProfile.bio || '未填写' }}</text>
        <image class="arrow-right" src="/static/icons/wechat-icon.svg" mode="aspectFit"></image>
      </view>

      <!-- 生日 -->
      <view class="form-item" @click="handleBirthdayEdit">
        <text class="form-label">生日</text>
        <text class="form-value">{{ userProfile.birthday || '未设置' }}</text>
        <image class="arrow-right" src="/static/icons/wechat-icon.svg" mode="aspectFit"></image>
      </view>

      <!-- 地区 -->
      <view class="form-item" @click="handleRegionEdit">
        <text class="form-label">地区</text>
        <text class="form-value">{{ userProfile.region || '未设置' }}</text>
        <image class="arrow-right" src="/static/icons/wechat-icon.svg" mode="aspectFit"></image>
      </view>

      <!-- 教育信息 -->
      <view class="form-item" @click="handleEducationEdit">
        <text class="form-label">教育信息</text>
        <text class="form-value">{{ userProfile.educationInfo.length > 0 ? '已设置' : '添加教育信息' }}</text>
        <image class="arrow-right" src="/static/icons/wechat-icon.svg" mode="aspectFit"></image>
      </view>

      <!-- 工作信息 -->
      <view class="form-item" @click="handleWorkEdit">
        <text class="form-label">工作信息</text>
        <text class="form-value">{{ userProfile.workInfo.length > 0 ? '已设置' : '添加工作信息' }}</text>
        <image class="arrow-right" src="/static/icons/wechat-icon.svg" mode="aspectFit"></image>
      </view>

      <!-- 身份状态 -->
      <view class="form-item" @click="handleStatusEdit">
        <text class="form-label">身份状态</text>
        <text class="form-value">{{ userProfile.status || '更新你的状态吧' }}</text>
        <image class="arrow-right" src="/static/icons/wechat-icon.svg" mode="aspectFit"></image>
      </view>

      <!-- 感兴趣 -->
      <view class="form-item" @click="handleInterestsEdit">
        <text class="form-label">感兴趣</text>
        <text class="form-value">{{ userProfile.interests.length > 0 ? userProfile.interests.join(', ') : '未设置' }}</text>
        <image class="arrow-right" src="/static/icons/wechat-icon.svg" mode="aspectFit"></image>
      </view>
    </view>

    <!-- 提示文字 -->
    <view class="tip-text">请确保您的个人信息真实有效，这将有助于您获得更好的用户体验</view>
  </view>
</template>

<script>
import profileEditApi from "../../api/profile-edit.js";

export default {
  data() {
    return {
      userProfile: {
        userName: "",
        gender: "",
        avatarUrl: "",
        bio: "",
        birthday: "",
        region: "",
        educationInfo: [],
        workInfo: [],
        status: "",
        interests: [],
      },
      loading: false,
    };
  },

  onLoad() {
    // 加载用户资料
    this.loadUserProfile();
  },

  methods: {
    /**
     * 加载用户资料
     */
    async loadUserProfile() {
      try {
        this.loading = true;
        const res = await profileEditApi.getUserProfile();
        if (res.code === 0) {
          this.userProfile = res.data;
        } else {
          uni.showToast({
            title: "获取资料失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("加载用户资料失败:", error);
        uni.showToast({
          title: "获取资料失败",
          icon: "none",
        });
      } finally {
        this.loading = false;
      }
    },

    /**
     * 处理返回按钮点击
     */
    handleBack() {
      uni.navigateBack();
    },

    /**
     * 处理保存按钮点击
     */
    async handleSave() {
      try {
        this.loading = true;
        const res = await profileEditApi.saveUserProfile(this.userProfile);
        if (res.code === 0) {
          uni.showToast({
            title: "保存成功",
            icon: "success",
          });
          // 保存成功后返回上一页
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          uni.showToast({
            title: res.message || "保存失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("保存用户资料失败:", error);
        uni.showToast({
          title: "保存失败",
          icon: "none",
        });
      } finally {
        this.loading = false;
      }
    },

    /**
     * 处理头像更换
     */
    async handleAvatarChange() {
      uni.chooseImage({
        count: 1,
        sizeType: ["original", "compressed"],
        sourceType: ["album", "camera"],
        success: async (res) => {
          const tempFilePath = res.tempFilePaths[0];
          try {
            // 显示加载提示
            uni.showLoading({
              title: "上传中...",
            });

            // 上传头像
            const uploadRes = await profileEditApi.uploadAvatar(tempFilePath);

            // 隐藏加载提示
            uni.hideLoading();

            if (uploadRes.code === 0) {
              this.userProfile.avatarUrl = uploadRes.data.avatarUrl;
              uni.showToast({
                title: "上传成功",
                icon: "success",
              });
            } else {
              uni.showToast({
                title: uploadRes.message || "上传失败",
                icon: "none",
              });
            }
          } catch (error) {
            uni.hideLoading();
            console.error("上传头像失败:", error);
            uni.showToast({
              title: "上传失败",
              icon: "none",
            });
          }
        },
      });
    },

    /**
     * 处理性别选择
     */
    handleGenderSelect(gender) {
      this.userProfile.gender =
        this.userProfile.gender === gender ? "" : gender;
    },

    /**
     * 处理简介编辑
     */
    handleBioEdit() {
      uni.showModal({
        title: "编辑简介",
        content: "请输入个人简介",
        editable: true,
        placeholderText: "输入个人简介（最多100字）",
        success: (res) => {
          if (res.confirm) {
            this.userProfile.bio = res.content || "";
          }
        },
      });
    },

    /**
     * 处理生日编辑
     */
    handleBirthdayEdit() {
      // 简化版实现，实际项目中可以使用日期选择器
      uni.showModal({
        title: "编辑生日",
        content: "请输入生日",
        editable: true,
        placeholderText: "YYYY-MM-DD",
        success: (res) => {
          if (res.confirm) {
            this.userProfile.birthday = res.content || "";
          }
        },
      });
    },

    /**
     * 处理地区编辑
     */
    handleRegionEdit() {
      // 简化版实现，实际项目中可以使用地区选择器
      uni.showModal({
        title: "编辑地区",
        content: "请输入地区",
        editable: true,
        placeholderText: "例如：北京",
        success: (res) => {
          if (res.confirm) {
            this.userProfile.region = res.content || "";
          }
        },
      });
    },

    /**
     * 处理教育信息编辑
     */
    handleEducationEdit() {
      uni.showToast({
        title: "教育信息编辑功能待实现",
        icon: "none",
      });
    },

    /**
     * 处理工作信息编辑
     */
    handleWorkEdit() {
      uni.showToast({
        title: "工作信息编辑功能待实现",
        icon: "none",
      });
    },

    /**
     * 处理身份状态编辑
     */
    handleStatusEdit() {
      uni.showModal({
        title: "更新状态",
        content: "请输入当前身份状态",
        editable: true,
        placeholderText: "例如：在职、求职中、学生等",
        success: (res) => {
          if (res.confirm) {
            this.userProfile.status = res.content || "";
          }
        },
      });
    },

    /**
     * 处理感兴趣编辑
     */
    handleInterestsEdit() {
      uni.showModal({
        title: "编辑感兴趣",
        content: "请输入感兴趣的内容，用逗号分隔",
        editable: true,
        placeholderText: "例如：前端开发,Java,Python",
        success: (res) => {
          if (res.confirm && res.content) {
            this.userProfile.interests = res.content
              .split(",")
              .map((item) => item.trim())
              .filter((item) => item);
          } else if (res.confirm) {
            this.userProfile.interests = [];
          }
        },
      });
    },
  },
};
</script>

<style lang="scss">
/* 导入样式文件 */
@import "./profile-edit.scss";
</style>